<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redis;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class ValidateToken
{
    public function handle($request, Closure $next)
    {
        $auth = $request->header('Authorization');
        $token = substr($auth, strlen('Bearer '));
        if(!$token){
            fun_respon(0,'token为空');
        }
        $info = Crypt::decrypt($token);

        if (!isset($info['openid']) && empty($info['openid'])) {
            fun_respon(0, 'token错误');
        }

        $redis_token = Redis::get('token_' . $info['openid']);
        if (!$redis_token || $token != $redis_token) {
            fun_respon(0, '授权已过期', 401);
        }
        $request->offsetSet('openid', $info['openid']);
        return $next($request);
    }
}
